<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Button, Tag, Empty, message, Dropdown, Popconfirm } from 'ant-design-vue'
import { PlusOutlined, EditOutlined, DeleteOutlined, CopyOutlined, EllipsisOutlined, StarOutlined, MessageOutlined, CalendarOutlined } from '@ant-design/icons-vue'
import FilterSearch from '@/components/FilterSearch.vue'

// 角色数据
const roles = ref([])
const loading = ref(true)
const router = useRouter()

// 响应式检测
const isMobile = ref(false)
const checkScreenSize = () => {
	isMobile.value = window.innerWidth < 768
}

// 搜索和筛选状态
const currentFilters = ref({
	searchText: '',
	category: null,
	status: null
})


// 分类选项
const categoryOptions = ref([
	{ label: '全部分类', value: null },
	{ label: '助手工具', value: 'assistant' },
	{ label: '创意写作', value: 'creative' },
	{ label: '技术专家', value: 'technical' },
	{ label: '心理咨询', value: 'psychology' },
	{ label: '语言学习', value: 'language' },
	{ label: '娱乐游戏', value: 'entertainment' },
	{ label: '教育培训', value: 'education' },
	{ label: '商务助理', value: 'business' },
])

// 状态选项
const statusOptions = ref([
	{ label: '全部状态', value: null },
	{ label: '公开', value: true },
	{ label: '私有', value: false },
])

// 模拟角色数据
const mockRoles = [
	{
		id: 1,
		name: '智能助手',
		description: '我是一个智能助手，可以帮助你解答各种问题，提供实用的建议和信息。',
		personality: '友善、耐心、博学',
		background: '具备广泛的知识背景，擅长逻辑分析和问题解决。',
		avatar: '',
		tags: ['助手', '问答', '实用'],
		category: 'assistant',
		isPublic: true,
		conversations: 128,
		createdAt: '2024-01-10 10:00',
		updatedAt: '2024-01-15 14:30',
	},
	{
		id: 2,
		name: '文学创作伙伴',
		description: '擅长创意写作、诗歌创作和文学分析，让我们一起探索文字的魅力。',
		personality: '富有想象力、感性、文艺',
		background: '深厚的文学素养，熟悉各种写作技巧和文学流派。',
		avatar: '',
		tags: ['文学', '创作', '诗歌'],
		category: 'creative',
		isPublic: true,
		conversations: 89,
		createdAt: '2024-01-08 16:20',
		updatedAt: '2024-01-14 10:20',
	},
	{
		id: 3,
		name: '技术专家',
		description: '专注于编程技术、软件开发和技术咨询，为你的项目提供专业指导。',
		personality: '严谨、专业、创新',
		background: '多年软件开发经验，精通多种编程语言和技术栈。',
		avatar: '',
		tags: ['编程', '技术', '开发'],
		category: 'technical',
		isPublic: true,
		conversations: 156,
		createdAt: '2024-01-05 09:30',
		updatedAt: '2024-01-13 09:15',
	},
	{
		id: 4,
		name: '心理咨询师',
		description: '提供心理健康支持和情感疏导，倾听你的烦恼并给出专业建议。',
		personality: '温暖、理解、专业',
		background: '心理学专业背景，具备丰富的咨询经验。',
		avatar: '',
		tags: ['心理', '咨询', '倾听'],
		category: 'psychology',
		isPublic: false,
		conversations: 203,
		createdAt: '2024-01-03 14:45',
		updatedAt: '2024-01-12 15:45',
	},
]

// 筛选后的角色列表
const filteredRoles = computed(() => {
	let result = roles.value

	// 文本搜索
	if (currentFilters.value.searchText?.trim()) {
		const search = currentFilters.value.searchText.toLowerCase()
		result = result.filter(
			role =>
				role.name.toLowerCase().includes(search) ||
				role.description.toLowerCase().includes(search) ||
				role.tags.some(tag => tag.toLowerCase().includes(search))
		)
	}

	// 分类筛选
	if (currentFilters.value.category !== null) {
		result = result.filter(role => role.category === currentFilters.value.category)
	}

	// 状态筛选
	if (currentFilters.value.status !== null) {
		result = result.filter(role => role.isPublic === currentFilters.value.status)
	}

	return result.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
})

// 处理筛选变化
const handleFilterChange = (filters) => {
	currentFilters.value = {
		searchText: filters.searchText,
		category: filters.category,
		status: filters.rating // 复用rating参数作为status
	}
}

// 创建新角色
const createRole = () => {
	router.push('/roles/create')
}

// 编辑角色
const editRole = role => {
	router.push(`/roles/edit/${role.id}`)
}

// 复制角色
const duplicateRole = async role => {
	// 创建副本角色数据
	const newRole = {
		id: Date.now(),
		name: `${role.name} (副本)`,
		description: role.description,
		personality: role.personality,
		background: role.background,
		tags: [...role.tags],
		avatar: role.avatar,
		category: role.category,
		isPublic: false,
		conversations: 0,
		createdAt: new Date().toLocaleString('zh-CN'),
		updatedAt: new Date().toLocaleString('zh-CN'),
	}
	roles.value.unshift(newRole)
	message.success('角色复制成功')
}

// 删除角色
const deleteRole = roleId => {
	roles.value = roles.value.filter(role => role.id !== roleId)
	message.success('角色删除成功')
}


// 清空搜索
const clearSearch = () => {
	currentFilters.value = {
		searchText: '',
		category: null,
		status: null
	}
}

// 格式化时间显示
const formatTime = timeStr => {
	const date = new Date(timeStr)
	return date.toLocaleDateString('zh-CN')
}

// 获取分类显示名称
const getCategoryName = category => {
	const option = categoryOptions.value.find(opt => opt.value === category)
	return option ? option.label : category
}


// 组件挂载后加载数据
onMounted(() => {
	// 检测屏幕尺寸并添加监听器
	checkScreenSize()
	window.addEventListener('resize', checkScreenSize)

	setTimeout(() => {
		roles.value = mockRoles
		loading.value = false
	}, 800)
})
</script>

<template>
	<div class="page-container">

		<!-- 筛选搜索组件 -->
		<FilterSearch
			search-placeholder="搜索角色名称、描述或标签..."
			:category-options="categoryOptions"
			:rating-options="statusOptions"
			:show-rating-filter="true"
			@filter-change="handleFilterChange"
		/>

		<!-- 操作按钮 -->
		<div class="action-bar">
			<Button
				type="primary"
				size="large"
				@click="createRole"
				class="btn-gradient large"
			>
				<template #icon>
					<PlusOutlined />
				</template>
				创建角色
			</Button>
		</div>

		<!-- 角色列表 -->
		<div class="roles-section">
			<!-- 加载状态 -->
			<div
				v-if="loading"
				class="loading-state"
			>
				<div class="loading-text">加载中...</div>
				<div class="skeleton-roles">
					<div
						v-for="i in 6"
						:key="i"
						class="skeleton-role"
					></div>
				</div>
			</div>

			<!-- 角色网格 - 桌面端 -->
			<div v-else-if="filteredRoles.length > 0 && !isMobile" class="roles-grid">
				<div
					v-for="role in filteredRoles"
					:key="role.id"
					class="role-card card-base hoverable"
				>
					<!-- 角色头部信息 -->
					<div class="role-header">
						<div class="role-avatar">
							<img
								:src="role.avatar || `https://lh.ithxs.com/apis.php?act=def&seed=${role.id}`"
								:alt="role.name"
							/>
							<div
								class="status-badge"
								:class="{ 'is-public': role.isPublic, 'is-private': !role.isPublic }"
							>
								{{ role.isPublic ? '公开' : '私有' }}
							</div>
						</div>
						<div class="role-basic">
							<h3 class="role-name">{{ role.name }}</h3>
							<div class="role-stats">
								<div class="conversations">
									<MessageOutlined />
									<span>{{ role.conversations }}</span>
								</div>
								<div class="category">
									<StarOutlined />
									<span>{{ getCategoryName(role.category) }}</span>
								</div>
							</div>
						</div>
						<div class="role-actions">
							<Dropdown>
								<Button type="text" class="action-btn">
									<EllipsisOutlined />
								</Button>
								<template #overlay>
									<div class="action-menu">
										<div class="action-item" @click="editRole(role)">
											<EditOutlined /> 编辑
										</div>
										<div class="action-item" @click="duplicateRole(role)">
											<CopyOutlined /> 复制
										</div>
										<Popconfirm
											title="确定要删除这个角色吗？"
											ok-text="确定"
											cancel-text="取消"
											@confirm="deleteRole(role.id)"
										>
											<div class="action-item danger">
												<DeleteOutlined /> 删除
											</div>
										</Popconfirm>
									</div>
								</template>
							</Dropdown>
						</div>
					</div>

					<!-- 角色描述 -->
					<p class="role-description">{{ role.description }}</p>

					<!-- 标签 -->
					<div class="role-tags">
						<Tag
							v-for="tag in role.tags.slice(0, 3)"
							:key="tag"
							class="role-tag"
						>
							{{ tag }}
						</Tag>
						<span v-if="role.tags.length > 3" class="more-tags">
							+{{ role.tags.length - 3 }}
						</span>
					</div>

					<!-- 更新时间 -->
					<div class="role-meta">
						<CalendarOutlined />
						<span>更新于 {{ formatTime(role.updatedAt) }}</span>
					</div>
				</div>
			</div>

			<!-- 角色列表 - 移动端 -->
			<div v-else-if="filteredRoles.length > 0 && isMobile" class="roles-list-mobile">
				<div
					v-for="role in filteredRoles"
					:key="role.id"
					class="role-item-mobile"
				>
					<div class="role-content-mobile">
						<!-- 左侧头像 -->
						<div class="role-left">
							<div class="role-avatar-mobile">
								<img
									:src="role.avatar || `https://lh.ithxs.com/apis.php?act=def&seed=${role.id}`"
									:alt="role.name"
								/>
							</div>
							<div
								class="status-mobile"
								:class="{ 'is-public': role.isPublic, 'is-private': !role.isPublic }"
							>
								{{ role.isPublic ? '公开' : '私有' }}
							</div>
						</div>

						<!-- 中间信息 -->
						<div class="role-middle">
							<div class="role-name-mobile">{{ role.name }}</div>
							<div class="role-preview">{{ role.description.substring(0, 40) }}...</div>
							<div class="role-tags-mobile">
								<span
									v-for="tag in role.tags.slice(0, 2)"
									:key="tag"
									class="role-tag-mobile"
								>
									{{ tag }}
								</span>
							</div>
						</div>

						<!-- 右侧操作 -->
						<div class="role-right">
							<div class="role-stats-mobile">
								<div class="conversations-mobile">
									<MessageOutlined />
									<span>{{ role.conversations }}</span>
								</div>
								<div class="update-time-mobile">
									{{ formatTime(role.updatedAt) }}
								</div>
							</div>
							<Dropdown>
								<div class="more-btn">
									<EllipsisOutlined />
								</div>
								<template #overlay>
									<div class="action-menu">
										<div class="action-item" @click="editRole(role)">
											<EditOutlined /> 编辑
										</div>
										<div class="action-item" @click="duplicateRole(role)">
											<CopyOutlined /> 复制
										</div>
										<Popconfirm
											title="确定要删除吗？"
											ok-text="确定"
											cancel-text="取消"
											@confirm="deleteRole(role.id)"
										>
											<div class="action-item danger">
												<DeleteOutlined /> 删除
											</div>
										</Popconfirm>
									</div>
								</template>
							</Dropdown>
						</div>
					</div>
				</div>
			</div>

			<!-- 空状态 -->
			<Empty
				v-else
				class="empty-state"
				:description="currentFilters.searchText || currentFilters.category !== null || currentFilters.status !== null ? '没有找到匹配的角色' : '暂无角色'"
			>
				<template #image>
					<div class="empty-icon">🎭</div>
				</template>
				<template #description>
					<p class="empty-desc">
						{{
							currentFilters.searchText || currentFilters.category !== null || currentFilters.status !== null
								? '尝试调整搜索条件或筛选条件'
								: '创建你的第一个AI角色，开始精彩的对话之旅'
						}}
					</p>
				</template>
				<Button
					v-if="!currentFilters.searchText && currentFilters.category === null && currentFilters.status === null"
					type="primary"
					size="large"
					@click="createRole"
				>
					立即创建
				</Button>
			</Empty>
		</div>

	</div>
</template>

<script>
// 为标签生成颜色的辅助函数
export default {
	methods: {
		getTagColor(tag) {
			const colors = ['blue', 'green', 'orange', 'red', 'purple', 'cyan', 'magenta']
			const hash = tag.split('').reduce((a, b) => {
				a = (a << 5) - a + b.charCodeAt(0)
				return a & a
			}, 0)
			return colors[Math.abs(hash) % colors.length]
		},
	},
}
</script>

<style lang="scss" scoped>
@use '../styles/variables.scss' as v;

/* 操作栏样式 */
.action-bar {
	display: flex;
	justify-content: flex-end;
	margin-bottom: 24px;
}

/* 角色列表容器 */
.roles-section {
	min-height: 400px;
}

/* PC端卡片布局 */
.roles-grid {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
	gap: 20px;
	padding: 4px;
}

.role-card {
	padding: 20px;
	background: rgba(255, 255, 255, 0.9);
	backdrop-filter: blur(10px);
	border: 1px solid rgba(255, 255, 255, 0.3);
	border-radius: 16px;
	box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
	cursor: pointer;
	min-height: 260px;
	display: flex;
	flex-direction: column;

	&:hover {
		transform: translateY(-4px);
		box-shadow: 0 12px 48px rgba(0, 0, 0, 0.15);
		background: rgba(255, 255, 255, 0.95);
	}
}

.role-header {
	display: flex;
	align-items: flex-start;
	gap: 16px;
	margin-bottom: 16px;
	position: relative;
}

.role-avatar {
	position: relative;
	flex-shrink: 0;

	img {
		width: 54px;
		height: 54px;
		border-radius: 12px;
		object-fit: cover;
		border: 2px solid rgba(255, 255, 255, 0.6);
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}
}

.status-badge {
	position: absolute;
	top: -6px;
	right: -8px;
	padding: 2px 6px;
	border-radius: 8px;
	font-size: 10px;
	font-weight: 500;
	color: white;
	text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);

	&.is-public {
		background: linear-gradient(135deg, #52c41a, #73d13d);
	}

	&.is-private {
		background: linear-gradient(135deg, #faad14, #ffc53d);
	}
}

.role-basic {
	flex: 1;
	min-width: 0;
}

.role-name {
	font-size: 16px;
	font-weight: 700;
	color: #2c2c2c;
	margin: 0 0 8px 0;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.role-stats {
	display: flex;
	align-items: center;
	gap: 12px;
	font-size: 12px;
	color: #666;

	.conversations, .category {
		display: flex;
		align-items: center;
		gap: 4px;

		.anticon {
			font-size: 12px;
			color: #999;
		}
	}
}

.role-actions {
	flex-shrink: 0;

	.action-btn {
		color: #999;
		border: none;
		padding: 4px 8px;
		border-radius: 6px;
		transition: all 0.2s ease;

		&:hover {
			color: #667eea;
			background: rgba(102, 126, 234, 0.1);
		}
	}
}

.role-description {
	font-size: 13px;
	color: #555;
	line-height: 1.5;
	margin: 0 0 16px 0;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.role-tags {
	display: flex;
	flex-wrap: wrap;
	gap: 6px;
	align-items: center;
	margin-bottom: 16px;
}

.role-tag {
	font-size: 11px;
	padding: 4px 8px;
	border-radius: 12px;
	margin: 0;
	background: rgba(102, 126, 234, 0.1);
	color: #667eea;
	border: none;
}

.more-tags {
	font-size: 11px;
	color: #999;
	margin-left: 4px;
}

.role-meta {
	display: flex;
	align-items: center;
	gap: 6px;
	font-size: 11px;
	color: #999;
	margin-top: auto;

	.anticon {
		font-size: 11px;
	}
}

/* 移动端列表布局 */
.roles-list-mobile {
	display: flex;
	flex-direction: column;
	gap: 12px;
	padding: 4px;
}

.role-item-mobile {
	background: rgba(255, 255, 255, 0.9);
	backdrop-filter: blur(10px);
	border: 1px solid rgba(255, 255, 255, 0.3);
	border-radius: 12px;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
	transition: all 0.3s ease;

	&:active {
		transform: scale(0.98);
		background: rgba(255, 255, 255, 0.95);
	}
}

.role-content-mobile {
	display: flex;
	padding: 16px;
	gap: 12px;
	align-items: center;
}

.role-left {
	position: relative;
	flex-shrink: 0;
}

.role-avatar-mobile {
	img {
		width: 48px;
		height: 48px;
		border-radius: 10px;
		object-fit: cover;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}
}

.status-mobile {
	position: absolute;
	top: -4px;
	right: -6px;
	padding: 1px 4px;
	border-radius: 6px;
	font-size: 8px;
	font-weight: 500;
	color: white;

	&.is-public {
		background: #52c41a;
	}

	&.is-private {
		background: #faad14;
	}
}

.role-middle {
	flex: 1;
	min-width: 0;
	padding-right: 12px;
}

.role-name-mobile {
	font-size: 15px;
	font-weight: 600;
	color: #2c2c2c;
	margin-bottom: 4px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.role-preview {
	font-size: 12px;
	color: #666;
	line-height: 1.4;
	margin-bottom: 8px;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.role-tags-mobile {
	display: flex;
	gap: 4px;
	flex-wrap: nowrap;
	overflow: hidden;
}

.role-tag-mobile {
	font-size: 10px;
	padding: 2px 6px;
	border-radius: 8px;
	background: rgba(102, 126, 234, 0.1);
	color: #667eea;
	flex-shrink: 0;
}

.role-right {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	gap: 8px;
	flex-shrink: 0;
}

.role-stats-mobile {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	gap: 4px;
	font-size: 11px;
	color: #999;
}

.conversations-mobile {
	display: flex;
	align-items: center;
	gap: 4px;

	.anticon {
		font-size: 10px;
	}
}

.update-time-mobile {
	font-size: 10px;
	color: #bbb;
}

.more-btn {
	padding: 4px 8px;
	border-radius: 6px;
	color: #999;
	cursor: pointer;
	transition: all 0.2s ease;

	&:hover {
		color: #667eea;
		background: rgba(102, 126, 234, 0.1);
	}
}

/* 下拉菜单样式 */
.action-menu {
	padding: 8px 0;
	background: white;
	border-radius: 8px;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.action-item {
	display: flex;
	align-items: center;
	gap: 8px;
	padding: 8px 16px;
	cursor: pointer;
	transition: background-color 0.2s ease;
	font-size: 13px;

	&:hover {
		background: #f5f5f5;
	}

	&.danger {
		color: #ff4d4f;

		&:hover {
			background: rgba(255, 77, 79, 0.1);
		}
	}

	.anticon {
		font-size: 12px;
	}
}

/* 加载状态样式 */
.skeleton-roles {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
	gap: 20px;
	padding: 4px;
}

.skeleton-role {
	height: 260px;
	background: rgba(255, 255, 255, 0.6);
	backdrop-filter: blur(5px);
	border-radius: 16px;
	border: 1px solid rgba(255, 255, 255, 0.2);
	position: relative;
	overflow: hidden;

	&::before {
		content: '';
		position: absolute;
		top: 0;
		left: -100%;
		width: 100%;
		height: 100%;
		background: linear-gradient(
			90deg,
			transparent,
			rgba(255, 255, 255, 0.6),
			transparent
		);
		animation: skeleton-loading 1.8s infinite;
	}
}

@keyframes skeleton-loading {
	0% {
		left: -100%;
	}
	100% {
		left: 100%;
	}
}


/* 响应式设计 */
@media (max-width: v.$breakpoint-mobile) {
	.roles-grid {
		grid-template-columns: 1fr;
		gap: 12px;
	}

	.skeleton-roles {
		grid-template-columns: 1fr;
	}

	.action-bar {
		justify-content: center;
	}
}


@media (max-width: 480px) {
	.role-content-mobile {
		padding: 12px;
		gap: 10px;
	}

	.role-avatar-mobile img {
		width: 40px;
		height: 40px;
		border-radius: 8px;
	}

	.role-name-mobile {
		font-size: 14px;
	}

	.role-preview {
		font-size: 11px;
	}

	.role-tag-mobile {
		font-size: 9px;
		padding: 1px 4px;
	}

}
</style>
